/**
 * Created by admin on 2020/7/31.
 */
import { GlobalDatas } from './GlobalDatas'
import axios from 'axios'
// import Bus from './Bus'
import { Message } from 'element-ui'
import { Loading } from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
// 方法一：将对象序列化，多个对象之间用&拼接
// qs.stringify()	转换成查询字符串
// let comments = {content: this.inp  utValue}
// let comValue = qs.stringify(comments)
// 方法二：将序列化的内容拆分成一个个单一的对象
// qs.parse() 转换成json对象
// let comValue = qs.parse(comments)
const requset = axios.create()
let cancel
const promiseArr = {}

const CancelToken = axios.CancelToken

const index = 0

// 响应时间
requset.defaults.timeout = 30000
// 配置cookie
requset.defaults.withCredentials = true
// 配置请求头（根据协议定）
requset.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8;'
// 配置接口地址
requset.defaults.baseURL = GlobalDatas.baseUrl
let loadingInstance = '' // 全屏loading实例
let IsLoading = false// 是否添加loading
// POST传参序列化(添加请求拦截器)
requset.interceptors.request.use(
  (config) => {
    /* token放到header中 */
    // if (window.sessionStorage.getItem('token')) {
    //   const str = window.sessionStorage.getItem('token')
    //   const token = str || null
    //   token && (config.headers.Authorization = token)
    // }
    const token = 'Bearer test1'
    token && (config.headers.Authorization = token)
    if (IsLoading) {
      loadingInstance = Loading.service({
        lock: true,
        text: '加载中',
        spinner: 'el-icon-loading'
      })
    }
    return config
  },
  (err) => {
    Message({
      message: err,
      type: 'warning'
    })
    return Promise.reject(err)
  }
)

// 返回状态判断(添加响应拦截器)
requset.interceptors.response.use(
  (res) => {
    // 这里根据后端提供的数据进行对应的处理
    const netData = res
    if (netData.status === 200) {
      if (IsLoading) {
        loadingInstance.close()
      }
      return Promise.resolve(netData)
    } else {
      let errMessage = '未知错误'
      if (netData.status) {
        switch (netData.status) {
          case 400:
            errMessage = '错误的请求'
            break
          case 401:
            errMessage = '未授权，请重新登录'
            break
          case 403:
            errMessage = '拒绝访问'
            break
          case 404:
            errMessage = '请求错误,未找到该资源'
            break
          case 405:
            errMessage = '请求方法未允许'
            break
          case 408:
            errMessage = '请求超时'
            break
          case 500:
            errMessage = '服务器端出错'
            break
          case 501:
            errMessage = '网络未实现'
            break
          case 502:
            errMessage = '网络错误'
            break
          case 503:
            errMessage = '服务不可用'
            break
          case 504:
            errMessage = '网络超时'
            break
          case 505:
            errMessage = 'http版本不支持该请求'
            break
          default:
            errMessage = `其他连接错误 --${netData.status}`
        }
      } else {
        errMessage = '无法连接到服务器！'
      }
      Message({
        message: errMessage,
        type: 'warning'
      })
      return Promise.resolve(false)
    }
  },
  (error) => {
    console.log(error)
    loadingInstance.close()
    Message({
      message:"连接超时",
      type: 'warning'
    })
    return Promise.resolve(false)
  }
)
// 发送请求
export function post (url, params, isloading) {
  IsLoading = isloading
  return new Promise((resolve, reject) => {
    const netParams = params
    requset
      .post(url, netParams, {
        cancelToken: new CancelToken((c) => {
          cancel = c
        })
      })
      .then(
        (res) => {
          resolve(res.data)
        },
        (err) => {
          reject(err.data)
        }
      )
      .catch((err) => {
        reject(err)
      })
  })
}
export function get (url, params, isloading) {
  IsLoading = isloading
  return new Promise((resolve, reject) => {
    requset
      .get(
        url,
        { params: params },
        {
          cancelToken: new CancelToken((c) => {
            cancel = c
          })
        }
      )
      .then((res) => {
        resolve(res.data)
      })
      .catch((err) => {
        loadingInstance.close()
        Message({
          message:"连接超时",
          type: 'warning'
        })
        reject(err)
      })
  })
}
